package com.ahdy.controller;

import com.ahdy.entity.Medication;
import com.ahdy.service.BaiduOcrService;
import com.ahdy.service.MedicationService;
import com.ahdy.tool.MedicationDataCleaner;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 药物信息管理控制器
 * 提供药物CRUD操作和OCR识别功能
 *
 * @author ahdy
 * @version 2.0
 */
@Slf4j
@RestController
@RequestMapping("/api/medications")
public class MedicationController {

    @Autowired
    private MedicationService medicationService;

    @Autowired
    private BaiduOcrService baiduOcrService;

    @Autowired
    private MedicationDataCleaner medicationDataCleaner;

    // ==================== OCR相关接口 ====================

    /**
     * 通过图片OCR识别添加药物信息
     *
     * @param requestBody 包含图片路径的请求体
     * @return 响应结果，包含药物基本信息和额外字段
     */
    @PostMapping("/ocr/extract")
    public ResponseEntity<Map<String, Object>> extractMedicationFromImage(@RequestBody Map<String, String> requestBody) {
        String imagePath = requestBody.get("imagePath");
        log.info("开始通过OCR识别药物信息，图片路径: {}", imagePath);

        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 参数验证
            if (imagePath == null || imagePath.trim().isEmpty()) {
                return buildErrorResponse("图片路径不能为空", HttpStatus.BAD_REQUEST);
            }

            // 2. OCR识别
            String ocrText = performOcrRecognition(imagePath.trim());
            if (ocrText == null || ocrText.trim().isEmpty()) {
                return buildErrorResponse("OCR识别结果为空，请确保图片清晰且包含药品信息", HttpStatus.BAD_REQUEST);
            }

            // 3. 提取药物信息
            Map<String, Object> medicationInfo = medicationDataCleaner.extractMedicationInfo(ocrText);
            if (!medicationDataCleaner.isValidMedicationInfo(medicationInfo)) {
                response.put("success", false);
                response.put("message", "提取的药物信息不完整或无效，请检查图片内容");
                response.put("ocrText", ocrText);
                response.put("extractedInfo", medicationInfo);
                return ResponseEntity.badRequest().body(response);
            }

            // 4. 保存到数据库
            Medication medication = (Medication) medicationInfo.get("medication");
            Integer medicationId = medicationService.addMedication(medication);
            Medication savedMedication = medicationService.getMedicationById(medicationId);

            // 5. 构建完整返回数据
            Map<String, Object> completeData = buildCompleteResponseData(savedMedication, medicationInfo);

            response.put("success", true);
            response.put("message", "通过OCR识别并添加药物信息成功");
            response.put("data", completeData);
            response.put("ocrText", ocrText);

            log.info("OCR药物信息提取成功，药物ID: {}, 名称: {}", medicationId, savedMedication.getName());
            return ResponseEntity.status(HttpStatus.CREATED).body(response);

        } catch (Exception e) {
            log.error("OCR药物信息提取过程发生异常: {}", e.getMessage(), e);
            return buildErrorResponse("系统异常: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 批量通过OCR识别添加药物信息
     *
     * @param requestBody 包含图片路径列表的请求体
     * @return 批量处理结果
     */
    @PostMapping("/ocr/batch-extract")
    public ResponseEntity<Map<String, Object>> batchExtractMedicationsFromImages(@RequestBody Map<String, List<String>> requestBody) {
        List<String> imagePaths = requestBody.get("imagePaths");

        log.info("开始批量OCR识别药物信息，图片数量: {}", imagePaths != null ? imagePaths.size() : 0);

        if (imagePaths == null || imagePaths.isEmpty()) {
            return buildErrorResponse("图片路径列表不能为空", HttpStatus.BAD_REQUEST);
        }

        Map<String, Object> response = new HashMap<>();

        try {
            List<Map<String, Object>> results = new ArrayList<>();
            int successCount = 0;
            int failureCount = 0;

            for (int i = 0; i < imagePaths.size(); i++) {
                String imagePath = imagePaths.get(i);
                Map<String, Object> itemResult = processSingleImage(i, imagePath);

                if ((Boolean) itemResult.get("success")) {
                    successCount++;
                } else {
                    failureCount++;
                }

                results.add(itemResult);
            }

            response.put("success", true);
            response.put("message", String.format("批量处理完成，成功: %d, 失败: %d", successCount, failureCount));
            response.put("totalCount", imagePaths.size());
            response.put("successCount", successCount);
            response.put("failureCount", failureCount);
            response.put("results", results);

            log.info("批量OCR处理完成，总数: {}, 成功: {}, 失败: {}", imagePaths.size(), successCount, failureCount);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("批量OCR处理发生异常: {}", e.getMessage(), e);
            return buildErrorResponse("批量处理异常: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * OCR预览接口（不保存到数据库）
     *
     * @param requestBody 包含OCR文字的请求体
     * @return 预览结果
     */
    @PostMapping("/ocr/preview")
    public ResponseEntity<Map<String, Object>> previewMedicationFromOcr(@RequestBody Map<String, String> requestBody) {
        String ocrText = requestBody.get("ocrText");

        log.info("开始预览OCR药物信息提取，文字长度: {}", ocrText != null ? ocrText.length() : 0);

        if (ocrText == null || ocrText.trim().isEmpty()) {
            return buildErrorResponse("OCR文字不能为空", HttpStatus.BAD_REQUEST);
        }

        try {
            // 提取药物信息但不保存到数据库
            Map<String, Object> medicationInfo = medicationDataCleaner.extractMedicationInfo(ocrText);
            boolean isValid = medicationDataCleaner.isValidMedicationInfo(medicationInfo);

            // 创建预览数据
            Map<String, Object> previewData = medicationDataCleaner.createCompleteMedicationData(medicationInfo);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "药物信息提取完成");
            response.put("medicationInfo", previewData);
            response.put("isValid", isValid);
            response.put("validationMessage", isValid ? "药物信息有效，可以保存" : "药物信息不完整，建议手动补充");

            log.info("OCR预览完成，提取状态: {}", isValid ? "有效" : "无效");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("预览药物信息失败: {}", e.getMessage(), e);
            return buildErrorResponse("提取药物信息失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // ==================== 原有CRUD接口（保持不变）====================

    /**
     * 添加药物信息
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addMedication(@Valid @RequestBody Medication medication) {
        Map<String, Object> response = new HashMap<>();

        try {
            log.info("添加药物信息: {}", medication.getName());

            Integer id = medicationService.addMedication(medication);
            Medication savedMedication = medicationService.getMedicationById(id);

            response.put("success", true);
            response.put("code", 200);
            response.put("message", "添加药物信息成功");
            response.put("data", savedMedication);

            return ResponseEntity.status(HttpStatus.CREATED).body(response);

        } catch (Exception e) {
            log.error("添加药物信息失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("code", 500);
            response.put("message", "添加药物信息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 更新药物信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateMedication(@PathVariable Integer id, @Valid @RequestBody Medication medication) {
        medication.setId(id);
        int rows = medicationService.updateMedication(medication);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            Medication updatedMedication = medicationService.getMedicationById(id);
            response.put("success", true);
            response.put("code", 200);
            response.put("message", "更新药物信息成功");
            response.put("data", updatedMedication);
        } else {
            response.put("success", false);
            response.put("code", 404);
            response.put("message", "药物信息不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 删除药物信息
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteMedication(@PathVariable Integer id) {
        int rows = medicationService.deleteMedication(id);

        Map<String, Object> response = new HashMap<>();
        if (rows > 0) {
            response.put("success", true);
            response.put("code", 200);
            response.put("message", "删除药物信息成功");
        } else {
            response.put("success", false);
            response.put("code", 404);
            response.put("message", "药物信息不存在");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID查询药物信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getMedicationById(@PathVariable Integer id) {
        Medication medication = medicationService.getMedicationById(id);

        Map<String, Object> response = new HashMap<>();
        if (medication != null) {
            response.put("success", true);
            response.put("code", 200);
            response.put("message", "获取药物信息成功");
            response.put("data", medication);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("code", 404);
            response.put("message", "药物信息不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
    }

    /**
     * 查询所有药物信息
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllMedications() {
        List<Medication> medications = medicationService.getAllMedications();

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("code", 200);
        response.put("message", "获取药物列表成功");
        response.put("data", medications);
        response.put("count", medications.size());
        return ResponseEntity.ok(response);
    }

    /**
     * 根据名称模糊查询药物信息
     */
    @GetMapping("/search/name")
    public ResponseEntity<Map<String, Object>> getMedicationsByName(@RequestParam String name) {
        List<Medication> medications = medicationService.getMedicationsByNameLike(name);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("code", 200);
        response.put("message", "按名称搜索药物成功");
        response.put("data", medications);
        response.put("count", medications.size());
        return ResponseEntity.ok(response);
    }

    /**
     * 根据类型查询药物信息
     */
    @GetMapping("/search/type")
    public ResponseEntity<Map<String, Object>> getMedicationsByType(@RequestParam Medication.MedicationType type) {
        List<Medication> medications = medicationService.getMedicationsByType(type);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("code", 200);
        response.put("message", "按类型搜索药物成功");
        response.put("data", medications);
        response.put("count", medications.size());
        return ResponseEntity.ok(response);
    }

    /**
     * 根据生产厂家模糊查询药物信息
     */
    @GetMapping("/search/manufacturer")
    public ResponseEntity<Map<String, Object>> getMedicationsByManufacturer(@RequestParam String manufacturer) {
        List<Medication> medications = medicationService.getMedicationsByManufacturerLike(manufacturer);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("code", 200);
        response.put("message", "按生产厂家搜索药物成功");
        response.put("data", medications);
        response.put("count", medications.size());
        return ResponseEntity.ok(response);
    }

    /**
     * 获取药物使用统计信息
     */
    @GetMapping("/statistics/usage")
    public ResponseEntity<Map<String, Object>> getMedicationUsageStatistics() {
        List<Map<String, Object>> statistics = medicationService.getMedicationUsageStatistics();

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("code", 200);
        response.put("message", "获取药物使用统计成功");
        response.put("data", statistics);
        return ResponseEntity.ok(response);
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 执行OCR识别
     */
    private String performOcrRecognition(String imagePath) throws Exception {
        try {
            String ocrText = baiduOcrService.basicRecognize(imagePath);
            log.info("OCR识别完成，识别文字长度: {}", ocrText != null ? ocrText.length() : 0);
            return ocrText;
        } catch (Exception e) {
            log.error("OCR识别失败: {}", e.getMessage());
            throw new Exception("OCR识别失败: " + e.getMessage());
        }
    }

    /**
     * 处理单张图片
     */
    private Map<String, Object> processSingleImage(int index, String imagePath) {
        Map<String, Object> itemResult = new HashMap<>();
        itemResult.put("index", index);
        itemResult.put("imagePath", imagePath);

        try {
            // OCR识别
            String ocrText = performOcrRecognition(imagePath.trim());

            if (ocrText == null || ocrText.trim().isEmpty()) {
                itemResult.put("success", false);
                itemResult.put("message", "OCR识别结果为空");
            } else {
                // 提取药物信息
                Map<String, Object> medicationInfo = medicationDataCleaner.extractMedicationInfo(ocrText);

                if (medicationDataCleaner.isValidMedicationInfo(medicationInfo)) {
                    // 保存到数据库
                    Medication medication = (Medication) medicationInfo.get("medication");
                    Integer medicationId = medicationService.addMedication(medication);
                    Medication savedMedication = medicationService.getMedicationById(medicationId);

                    // 构建完整返回数据
                    Map<String, Object> completeData = buildCompleteResponseData(savedMedication, medicationInfo);

                    itemResult.put("success", true);
                    itemResult.put("medication", completeData);
                } else {
                    itemResult.put("success", false);
                    itemResult.put("message", "提取的药物信息无效");
                    itemResult.put("ocrText", ocrText);
                    itemResult.put("extractedInfo", medicationInfo);
                }
            }
        } catch (Exception e) {
            log.error("处理图片 {} 时发生异常: {}", imagePath, e.getMessage());
            itemResult.put("success", false);
            itemResult.put("message", "处理异常: " + e.getMessage());
        }

        return itemResult;
    }

    /**
     * 构建完整的响应数据
     */
    private Map<String, Object> buildCompleteResponseData(Medication savedMedication, Map<String, Object> medicationInfo) {
        Map<String, Object> completeData = new HashMap<>();

        // 数据库中的标准字段
        completeData.put("id", savedMedication.getId());
        completeData.put("name", savedMedication.getName());
        completeData.put("type", savedMedication.getType());
        completeData.put("manufacturer", savedMedication.getManufacturer());
        completeData.put("description", savedMedication.getDescription());
        completeData.put("sideEffects", savedMedication.getSideEffects());
        completeData.put("createdAt", savedMedication.getCreatedAt());

        // 额外提取的字段（仅在响应中返回）
        completeData.put("singleDosage", medicationInfo.get("singleDosage"));
        completeData.put("dailyFrequency", medicationInfo.get("dailyFrequency"));
        completeData.put("specialInstructions", medicationInfo.get("specialInstructions"));

        return completeData;
    }

    /**
     * 构建错误响应
     */
    private ResponseEntity<Map<String, Object>> buildErrorResponse(String message, HttpStatus status) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return ResponseEntity.status(status).body(response);
    }
}
